package com.exampl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exampl.common.CustomException;
import com.exampl.common.R;
import com.exampl.domain.Category;
import com.exampl.domain.Dish;
import com.exampl.domain.DishFlavor;
import com.exampl.domain.Setmeal;
import com.exampl.dto.DishDto;
import com.exampl.service.CategoryService;
import com.exampl.service.DishFlavorService;
import com.exampl.service.DishService;
import com.exampl.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    DishService dishService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    RedisTemplate redisTemplate;

    // 添加菜品
    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        // 添加了菜品的数据，进行局部删除缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("保存成功！");
    }

    // 显示菜品
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name){
        Page<Dish> dishPage = new Page<Dish>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<DishDto>();
        // 添加条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<Dish>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        // 查询结果
        dishService.page(dishPage, lqw);
        // 拷贝结果
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();
        // 使用lambda表达式获取到分类名称，并且存到集合中
        List<DishDto> list = records.stream().map((data) -> {
            DishDto dishDto = new DishDto();
            // 将dish中的变量值赋值给dishDto
            BeanUtils.copyProperties(data, dishDto);
            Long id = data.getCategoryId();
            Category category = categoryService.getById(id);
            // 设置dishDto的CategoryName属性值
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        // 将上面得到的list集合存储到dishDtoPage中，并返回给前端
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    // 回显数据
    @GetMapping("/{id}")
    public R<DishDto> reserve(@PathVariable Long id){
        DishDto dishDto = dishService.getDishDto(id);
        return R.success(dishDto);
    }

    // 修改数据
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        // 修改了菜品的数据，进行局部删除缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功！");
    }

    // 删除数据
    @DeleteMapping
    public R<String> delete(String ids){
        List<Long> list = new ArrayList<Long>();
        String[] split = ids.split(",");
        for(String s:split){
            Long id = Long.valueOf(s);
            boolean b = dishService.isExist(id);
            if(b){
                // 该菜品存在于套餐中，抛出异常
                throw new CustomException("选中的菜品中存在于套餐中，无法删除！");
            }
            list.add(id);
        }
        // 判断该菜品是否在售
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<Dish>();
        dishLambdaQueryWrapper.in(Dish::getId, list);
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        int count = dishService.count(dishLambdaQueryWrapper);
        if(count > 0){
            throw new CustomException("该菜品在售，无法删除！");
        }
        // 删除口味
        for(Long id:list){
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<DishFlavor>();
            lqw.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(lqw);
        }
        // 删除菜品
        dishService.removeByIds(list);
        return R.success("删除成功！");
    }

    // 修改状态
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", condition = "#status == 0", allEntries = true)  // 停售菜品，删除全部
    @Transactional
    public R<String> updateStatus(@PathVariable Integer status, String ids){
        // 获取id值
        List<Long> list = new ArrayList<Long>();
        String[] idSplit = ids.split(",");
        for(String s:idSplit){
            Long id = Long.valueOf(s);
            list.add(id);
            // 当需要停售时，自动将在售该菜品的套餐停售
            if(status == 0){
                dishService.setMealExist(id);
            }
        }
        // 将所有值存入集合中
        List<Dish> dishList = new ArrayList<Dish>();
        for (Long aLong : list) {
            Dish dish = new Dish();
            dish.setId(aLong);
            dish.setStatus(status);
            dishList.add(dish);
        }
        dishService.updateBatchById(dishList);
        // 修改了菜品状态，需要对其进行清除缓存，全局删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改状态成功！");
    }

    // 添加套餐中显示分类的菜品，不对后台进行缓存
    @GetMapping("/list")
    public R<List<DishDto>> setMeal(Long categoryId, Integer status){
        // 初始化数组
        List<DishDto> dtoList = null;
        // 生成动态key
        String key = "dish_" + categoryId + "_" + status;
        // 从redis中获取数据
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        // 若redis中存储了菜品数据，则直接获取
        if(dtoList != null){
            return R.success(dtoList);
        }
        // 若不存在则进行数据库的查询
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<Dish>();
        lqw.eq(categoryId != null, Dish::getCategoryId, categoryId);
        lqw.eq(status != null, Dish::getStatus, status);
        List<Dish> list = dishService.list(lqw);
        dtoList = list.stream().map((data) -> {
            DishDto dishDto = new DishDto();
            // 将dish中的变量值赋值给dishDto
            BeanUtils.copyProperties(data, dishDto);
            Long id = data.getId();
            // 设置dishDto的口味属性值
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<DishFlavor>();
            lqw1.eq(DishFlavor::getDishId, id);
            List<DishFlavor> flavors = dishFlavorService.list(lqw1);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
        // 将数据存储到redis中，设置生存时间为一小时，不存储后台缓存
        if(status != null){
            redisTemplate.opsForValue().set(key, dtoList, 60, TimeUnit.MINUTES);
        }
        return R.success(dtoList);
    }
}
